<template>
  <el-dialog :title="title"
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="120px">
      <el-form-item label="通知标题：" prop="title" :style="{ display: 'inline-block' }">
        <el-input v-model="form.title" :style="{ width: formItemWidth + 'px' }" placeholder="请输入通知标题"/>
      </el-form-item>
      <el-form-item label="通知分类：" prop="event_type" :style="{ display: 'inline-block' }">
        <el-select v-model="form.event_type" :disabled="isEdit" clearable :style="{ width: formItemWidth + 'px' }">
          <el-option v-for="item in eventTypeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目范围：" prop="appid" :style="{ display: 'inline-block' }">
        <el-select v-model="form.appid" :disabled="isEdit" filterable clearable :style="{ width: formItemWidth + 'px' }">
          <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道范围：" prop="union_id" :style="{ display: 'inline-block' }">
        <el-select v-model="form.union_id" :disabled="isEdit" placeholder="请选择" filterable clearable multiple collapse-tags :style="{ width: formItemWidth + 'px' }">
          <el-option v-for="item in channelOptions" :key="item.channel_id" :label="`${item.name}(${item.channel_id})`" :value="item.channel_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="最低版本：" prop="min_version" :style="{ display: 'inline-block' }">
        <el-input v-model="form.min_version" :disabled="isEdit" :style="{ width: formItemWidth + 'px' }" placeholder="请输入最低版本"/>
      </el-form-item>
      <el-form-item label="定时发布：" prop="published_at" :style="{ display: 'inline-block' }">
        <el-date-picker v-model="form.published_at"
          :disabled="isEdit"
          :style="{ width: formItemWidth + 'px' }"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="通知正文：" prop="content">
        <VueEditor v-model="form.content"
          useCustomImageHandler
          :disabled="isView"
          :editorOptions="editorSettings"
          @image-added="handleEditorImageAdd"
        />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="详情按钮：" prop="btn_enable" style="">
            <el-switch v-model="form.btn_enable" :disabled="isEdit"></el-switch>
            <el-tooltip class="item" effect="dark" content="用于拉起产品内的窗口" placement="top">
              <svg-icon iconClass="question" size="16"></svg-icon>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="消息置顶：" prop="is_top" style="">
            <el-switch v-model="form.is_top" :disabled="isEdit"></el-switch>
            <el-tooltip class="item" effect="dark" content="开启，则该条消息在用户的通知列表中置顶" placement="top">
              <svg-icon iconClass="question" size="16"></svg-icon>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="form.btn_enable">
        <el-form-item label="详情按钮文本：" prop="btn_text" :style="{ display: 'inline-block' }" >
          <el-input v-model="form.btn_text" :disabled="isEdit" :style="{ width: formItemWidth + 'px' }" placeholder="请输入跳转按钮文本"/>
        </el-form-item>
        <el-form-item label="按钮跳转地址：" prop="btn_address" :style="{ display: 'inline-block' }">
          <el-input v-model="form.btn_address" :disabled="isEdit" :style="{ width: formItemWidth + 'px' }" placeholder="请输入跳转按钮地址"/>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :disabled="isView" @click="submitForm">{{ submitText }}</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getChannelByAppId } from '@/api/system/channel'
import { uploadApi } from '@/api/rights/rights'
import { addMessage, updateMessage, getMessageDetailById } from '@/api/operations/message'
import { VueEditor, Quill } from 'vue2-editor'
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', ImageResize)

export default {
  name: 'OperationsMessageAddDialog',
  components: {
    VueEditor
  },
  data () {
    const versionValidator = (rule, value, callback) => {
      if (/^\d+(\.\d+){3}$/.test(value)) {
        callback()
      } else {
        callback(new Error('不能为空且版本号格式为1.0.0.0'))
      }
    }

    return {
      id: '',
      type: '',
      visible: false,
      eventTypeOptions: [
        {
          label: '更新通知',
          value: 'upgrade'
        },
        {
          label: '活动通知',
          value: 'activity'
        },
        {
          label: '重要提醒',
          value: 'remind'
        }
      ],
      channelOptions: [],
      form: {
        published_at: '',
        min_version: '',
        union_id: '',
        appid: '',
        event_type: '',
        title: '',
        content: '',
        btn_enable: false,
        is_top: false,
        btn_text: '',
        btn_address: '',
        target_type: '',
        target_id: ''
      },
      rules: {
        title: { required: true, message: '不能为空，且长度限制255字符', max: 255 },
        event_type: { required: true, message: '不能为空' },
        appid: { required: true, message: '不能为空' },
        union_id: { required: true, message: '不能为空' },
        min_version: { required: true, validator: versionValidator },
        content: { required: true, message: '不能为空' }
      },
      formItemWidth: 260,
      editorSettings: {
        modules: {
          imageResize: {
            modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
          }
        }
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    title () {
      const typeText = this.isEdit ? '编辑' : this.isView ? '查看' : '新增'
      return `${typeText}通知公告`
    },
    submitText () {
      return this.isEdit ? '更新' : '新增'
    },
    isView () {
      return this.type === 'view'
    },
    isEdit () {
      return this.type === 'edit'
    }
  },
  watch: {
    id (val) {
      if (val) {
        this.getDetailById()
      } else {
        this.resetForm('form')
      }
    },
    type (val) {
      if (!val) {
        this.resetForm('form')
        return
      }

      if (val === 'create') {
        this.resetForm('form')
      }
    }
  },
  methods: {
    open (id, type) {
      this.visible = true
      this.id = id || ''
      this.type = type || 'create'
    },
    close () {
      this.visible = false
      this.id = ''
      this.type = ''
    },
    getChannelOptions () {
      const list = this.permission_projectList.map(item => item.app_id)
      getChannelByAppId({ app_ids: list.join(',') }).then(res => {
        this.channelOptions = res.data.list
      })
    },
    submit () {
      const params = { ...this.form }
      params.union_id = this.form.union_id.join(',')
      if (this.id && this.isEdit) {
        updateMessage(this.id, params).then(res => {
          if (res.code === 200) {
            this.close()
            this.$emit('update')
            this.msgSuccess('更新成功')
          }
        })
        return
      }

      addMessage(params).then(res => {
        if (res.code === 200) {
          this.close()
          this.$emit('update')
          this.msgSuccess('新增成功')
        }
      })
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    handleEditorImageAdd (file, Editor, cursorLocation, resetUploader) {
      const forms = new FormData()
      forms.append('file', file)
      uploadApi(forms).then(res => {
        const url = res.data?.url
        Editor.insertEmbed(cursorLocation, 'image', url)
        resetUploader()
      })
    },
    getDetailById () {
      getMessageDetailById(this.id).then(res => {
        const data = res.data
        const obj = { ...this.form, ...data }
        delete obj.id
        this.form = obj
      })
    }
  },
  created () {
    this.getChannelOptions()
  }
}
</script>

<style lang="scss" scoped>
  .svg-icon {
    margin-left: 5px;
    margin-top: 2px;
  }
</style>
